#include<stdio.h>
  2 #include<malloc.h>
  3 #define OK 1
  4 #define ERROR 0
  5 #define LIST_INIT_SIZE 100
  6 #define LISTINCREMENT 10
  7 #define ElemType int
  8
  9 typedef struct
 10 {
 11     int *elem;
 12     int length;
 13     int listsize;
 14 }SqList;
 15
 16 int InitList_Sq(SqList &L)
 17 {
 18     L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
 19     if(!L.elem) return 0;
 20     L.length=0;
 21     L.listsize=LIST_INIT_SIZE;
 22     return OK;
 23
 24 }
 25
 26 int Load_Sq(SqList &L)
 27 {
 28 // 输出顺序表中的所有元素
 29     int i;
 30     if(L.length==0) printf("The List is empty!");  // 请填空
 31     else
 32     {
 33         printf("The List is: ");
 34         for(i=0;i<L.length;i++) printf("%d ",L.elem[i]);  // 请填空
 35     }
 36     printf("\n");
 37     return OK;
 38 }
 39
 40 int ListInsert_Sq(SqList &L,int i,int e)
 41 {
 42
 43 // 算法2.4，在顺序线性表L中第i个位置之前插入新的元素e
 44 // i的合法值为1≤i≤L.length +1
 45 // 请补全代码
 46     ElemType *q,*p,*newbase;
 47    if(i<1||i>L.length+1) return ERROR;
 48    if(L.length>L.listsize)
 49    {
 50        newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
 51        if(!L.elem)
 52        return ERROR;
 53         L.elem=newbase;
 54        L.listsize+=LISTINCREMENT;
 55    }
 56
 57    q=&(L.elem[i-1]);
 58    for(p=&(L.elem[L.length-1]);p>=q;--p)
 59
 60        *(p+1)=*p;
 61        *q=e;
 62        ++L.length;
 63
 64    return OK;
 65
 66 }
 67
 68 int ListDelete_Sq(SqList &L,int i, int &e)
 69 {
 70 // 算法2.5,在顺序线性表L中删除第i个位置的元素，并用e返回其值
 71 // i的合法值为1≤i≤L.length
 72 // 请补全代码
 73     ElemType *q,*p;
 74     if(i<1||i>L.length) return ERROR;
 75     p=&(L.elem[i-1]);
 76     e=*p;
 77     q=L.elem+L.length-1;
 78     for(p++;p<=q;++p)
 79     *(p-1)=*p;
 80     --L.length;
 81     return OK;
 82 }
 83
 84 int main()
 85 {
 86     SqList T;
 87     int a, i;
 88     ElemType e, x;
 89     if(InitList_Sq(T))    // 判断顺序表是否创建成功
 90     {
 91         printf("A Sequence List Has Created.\n");
 92     }
 93     while(1)
 94     {
 95         printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");
 96         scanf("%d",&a);
 97         switch(a)
 98         {
 99             case 1: scanf("%d%d",&i,&x);
100                     if(!ListInsert_Sq(T,i,x)) printf("Insert Error!\n"); // 判断i值是否合法，请填空
101                     else printf("The Element %d is Successfully Inserted!\n",x);
102                     break;
103             case 2: scanf("%d",&i);
104                     if(!ListDelete_Sq(T,i,e)) printf("Delete Error!\n"); // 判断i值是否合法，请填空
105                     else printf("The Element %d is Successfully Deleted!\n",e);
106                     break;
107             case 3: Load_Sq(T);
108                     break;
109             case 0: return 1;
110         }
111     }
112 }
